<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/18
 * Time: 21:39
 */

namespace app\storage\controller;

use app\storage\model\ContainerModel;
use app\storage\model\ReelsModel;
use app\storage\service\CommonService;
use cmf\controller\AdminBaseController;
use think\Request;

class ContainerController extends AdminBaseController
{
    private $containerModel;
    private $commonService;
    use \app\storage\util\Common;
    public function __construct(CommonService $commonService, ContainerModel $containerModel,Request $request = null)
    {
        parent::__construct($request);
        $this->containerModel = $containerModel;
        $this->commonService = $commonService;
    }

    public function index()
    {
        $assign = $this->getAssignStorage();
        $this->assign($assign);
        return $this->fetch('index');
    }

    public function getContainer()
    {
        $where = $this->getWhere();
        $result = $this->containerModel->getContainer($where);
        return json($result);
    }

    public function addContainer()
    {
        $number = input('number');
        $standard = strtoupper(input('standard'));

        if (!preg_match('/^[C-Z]/', $standard)) {
            ajax_response(false, '容器规格抬头需C-Z间字母');
        }

        $maxCode = $this->containerModel->where('type', $standard)->max('container_code', false);
        $tenCode = -1;
        $strCode = $standard;
        if (isset($maxCode)) {
            $tenCode = intval(substr($maxCode, 1, 4));
        }
        if ($tenCode + intval($number) > 9999) {
            ajax_response(false, '该规格超过最大数量，最多还能生成' . (9999 - $tenCode) . '个');
        }
        for ($i = $tenCode + 1; $i < $tenCode + $number + 1; $i++) {
            $newCode = $strCode . str_pad($i, 4, '0', STR_PAD_LEFT);
            $insertCode[] = array(
                'uuid' => create_uuid(),
                'container_code' => $newCode,
                'type' => $standard,
                'status' => 0
            );
        }

        $result = true;
        if (!empty($insertCode)) {
            $result = $this->containerModel->insertAll($insertCode);
        }
        $msg = $result == true ? '生成成功' : '生成异常';
        ajax_response(boolval($result), $msg);
    }

    public function deleteContainer()
    {
        $where['container_code'] = input('containerCode');
        $containerReels = ReelsModel::all($where);
        if (count($containerReels)) {
            ajax_response(false, '请先清空容器内物料');
        } else {
            $result = $this->containerModel->where($where)->delete();
            $msg = $result == true ? '删除成功' : '删除失败';
            ajax_response(boolval($result), $msg);
        }
    }
}